package com.yjf.demo.component.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.yjf.demo.basic.user.entity.User;
import com.yjf.demo.common.SessionService;
import lombok.NonNull;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private SessionService sessionService;
    @Resource
    private SecurityProperties securityProperties;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request,
                                    @NonNull HttpServletResponse response,
                                    @NonNull FilterChain filterChain) throws ServletException, IOException {
        /*
              动态检查所有放行路径
              request.getServletPath() 可以自动剥离context-path后的路径
              SecurityConfig会自动处理context-path
              而JwtAuthenticationFilter需要自己手动处理
         */
        boolean needSkip = securityProperties.getUrls().stream()
                .anyMatch(url -> new AntPathMatcher().match(url, request.getServletPath()));
        if (needSkip) {
            filterChain.doFilter(request, response);
            return;
        }

        // 获取sessionId
        String sessionId = request.getHeader("access_token");
        if (StringUtils.isEmpty(sessionId)) {
            sendError(response, "缺少访问令牌");
            return;
        }

        // 验证Token有效性
        if (!sessionService.isExist(sessionId)) {
            sendError(response, "令牌已失效");
            return;
        }

        if (System.currentTimeMillis() > sessionService.getExpireTime(sessionId)) {
            sendError(response, "令牌已过期");
            sessionService.deleteSession(sessionId);
            return;
        }

        // 在现有验证通过后添加：
        if (System.currentTimeMillis() <= sessionService.getExpireTime(sessionId)) {
            User user = sessionService.getUserWithRenewal(sessionId);

            Authentication authentication = new UsernamePasswordAuthenticationToken(
                    user,
                    null,
                    null
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        filterChain.doFilter(request, response);
    }

    private void sendError(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.getWriter().write("{\"code\":401,\"message\":\"" + message + "\"}");
    }
}